import 'package:flutter/foundation.dart';
import '../models/mcp_tool.dart';
import 'mcp_service.dart';

/// 应用状态管理
class AppState extends ChangeNotifier {
  final McpService _mcpService = McpService();

  List<McpTool> _tools = [];
  McpTool? _selectedTool;
  Map<String, dynamic> _parameters = {};
  McpToolResult? _lastResult;
  bool _isLoading = false;
  bool _isCallingTool = false;  // 新增：工具调用中的加载状态
  String? _error;
  McpConfig? _config;
  final List<String> _logs = [];

  // Getters
  List<McpTool> get tools => _tools;
  McpTool? get selectedTool => _selectedTool;
  Map<String, dynamic> get parameters => _parameters;
  McpToolResult? get lastResult => _lastResult;
  bool get isLoading => _isLoading;
  bool get isCallingTool => _isCallingTool;  // 新增：暴露工具调用状态
  String? get error => _error;
  McpConfig? get config => _config;
  bool get isConnected => _mcpService.isConnected;
  List<String> get logs => List.unmodifiable(_logs);

  /// 添加日志
  void _log(String message) {
    final timestamp = DateTime.now().toString().substring(11, 23);
    _logs.add('$timestamp $message');
    print(message);
    notifyListeners();
  }

  /// 清除日志
  void clearLogs() {
    _logs.clear();
    notifyListeners();
  }

  /// 配置 MCP 连接
  Future<void> configure(McpConfig config) async {
    _setLoading(true);
    _error = null;

    try {
      _log('📡 开始连接: ${config.type == McpConnectionType.sse ? config.sseUrl : config.command}');
      
      await _mcpService.configure(config);
      _config = config;
      _log('✅ 连接成功');
      
      _log('🔧 开始获取工具列表...');
      await refreshTools();
      
      notifyListeners();
    } catch (e, stackTrace) {
      _log('❌ 连接失败: $e');
      _error = 'Failed to configure MCP: $e';
      notifyListeners();
      rethrow;
    } finally {
      _setLoading(false);
    }
  }

  /// 刷新工具列表
  Future<void> refreshTools() async {
    _setLoading(true);
    _error = null;

    try {
      _tools = await _mcpService.listTools();
      _log('✅ 获取到 ${_tools.length} 个工具');
      for (var tool in _tools) {
        _log('   - ${tool.name}');
      }
      notifyListeners();
    } catch (e, stackTrace) {
      _log('❌ 获取工具失败: $e');
      _error = 'Failed to refresh tools: $e';
      notifyListeners();
      rethrow;
    } finally {
      _setLoading(false);
    }
  }

  /// 选择工具
  void selectTool(McpTool? tool) {
    _selectedTool = tool;
    _parameters.clear();
    _lastResult = null;
    notifyListeners();
  }

  /// 更新参数
  void updateParameter(String name, dynamic value) {
    _parameters[name] = value;
    notifyListeners();
  }

  /// 调用工具
  Future<void> callTool() async {
    if (_selectedTool == null) return;

    _isCallingTool = true;  // 使用专门的工具调用状态
    _error = null;
    notifyListeners();  // 通知UI更新

    try {
      _log('🧪 调用工具: ${_selectedTool!.name}');
      _log('   参数: $_parameters');
      
      final result = await _mcpService.callTool(
        _selectedTool!.name,
        _parameters,
      );
      _lastResult = result;

      if (!result.success) {
        _log('❌ 工具调用失败: ${result.error}');
        _error = result.error;
      } else {
        _log('✅ 工具调用成功');
      }

      notifyListeners();
    } catch (e, stackTrace) {
      _log('❌ 调用异常: $e');
      _error = 'Failed to call tool: $e';
      _lastResult = McpToolResult(
        toolName: _selectedTool!.name,
        success: false,
        error: e.toString(),
      );
      notifyListeners();
    } finally {
      _isCallingTool = false;  // 恢复工具调用状态
      notifyListeners();
    }
  }

  /// 断开连接
  Future<void> disconnect() async {
    _log('🔌 断开连接');
    await _mcpService.disconnect();
    _tools = [];
    _selectedTool = null;
    _parameters.clear();
    _lastResult = null;
    _config = null;
    _log('✅ 已断开');
    notifyListeners();
  }

  /// 设置加载状态
  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  /// 清除错误
  void clearError() {
    _error = null;
    notifyListeners();
  }

  @override
  void dispose() {
    _mcpService.dispose();
    super.dispose();
  }
}
